const puppeteer = require('puppeteer')

const base = `https://movie.douban.com/subject/` //改成详情页地址
const doubanId = '1292063'
const videoBase = `https://movie.douban.com/trailer/257449`//预告片播放地址
const sleep = time => new Promise(resolve =>{
	setTimeout(resolve,time)
})

;(async () => {  //定义匿名函数
	console.log('Start visit the target page')
	const browser = await puppeteer.launch({ //启动浏览器
		args: ['--no-sandbox'],
		dumpio : false
	})

	const page = await browser.newPage() //得到封面图
	await page.goto(base + doubanId, {   //爬虫的网址
		waitUntil : 'networkidle2' //当网络空闲加载完毕
	})

	await sleep(1000) //等待1s,使页面彻底加载完毕

	//这个是在浏览器中执行的
	//判断下浏览器中是不是有jquery
	//如果有，可以直接使用
	const result = await page.evaluate( () => { 
		var $ = window.$;
		var it = $('.related-pic-video')
		if(it && it.length > 0){
			var link = it.attr('href')
			//var cover = it.find('img').attr('src')
			var str = it.attr('style').split('(')[1];
			var cover = str.substr(0 , str.length-1);	
			return {
				link,
				cover
			}
		}
		return {};
	})

	let video       //得到视频图片
	if (result.link) {
		await page.goto(result.link, {
			waitUntil : 'networkidle2' //当网络空闲加载完毕
		})
		await sleep(2000) //等待2s

		video = await page.evaluate( ()=> {
			var $ = window.$
			var it = $('source')
			if(it && it.length > 0){
				return it.attr('src')
			}

			return ''
		})
	}

	const data = {
		video,
		doubanId,
		cover: result.cover
	}

	browser.close(); //关闭浏览器

	//console.log(result)
	process.send(data);
	process.exit(0);

})()